$(document).ready(function () {

    $("#storeSelect").selectpicker();
    $("#employeeSelect").selectpicker();
    $("#accountMoneySelect").selectpicker();
    $("#supplierSelect").selectpicker();
    $('#inputOrderTable').DataTable({
        destroy: true,
        searching: false,
        paging: true,//表格分页
        lengthChange: false
    });
    $('#productTable').DataTable({
        destroy: true,
        searching: false,
        paging: true,//表格分页
        lengthChange: false
    });
    toastr.options = {
        "closeButton": true,
        "debug": false,
        "progressBar": true,
        "positionClass": "toast-top-right",
        "onclick": null,
        "showDuration": "400",
        "hideDuration": "1000",
        "timeOut": "7000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    }

    setInputOrderNumber($("#inputOrderNumber"))
    setInputOrderDate($("#inpDate"))
    listEmployees($("#employeeSelect"))
    listStores($("#storeSelect"))
    listMoneyAccount($("#accountMoneySelect"))
    listSupplier($("#supplierSelect"))
    //失去焦点事件
    // $('#inputNumber' + product.id).blur(function (){
    //     //数量和进价相乘,设置到金额一列
    //
    //
    // })

});

function listAllProductByStoreId(){
    //获取选中的id
    let stoId=$("#storeSelect").val()
    //获取数据
    $.get('/admin/business/inputReback/getProductByStore/'+stoId,{},function (resp){
        //数据填充到表格中
        $("#productTable").DataTable({
            destroy: true,
            //数据源
            data: resp.data.products,
            //取消搜索栏
            bFilter: false,
            bLengthChange: false,
            paging: false,//表格分页,
            //给每列赋值
            columns: [
                {
                    data: 'id', render: function (data, type, row, meta) {
                        return '<input name="inp-product-box" class="inp-product-box" type="checkbox" value="' + row.id + '">'
                    }
                },
                {
                    data: 'id', render: function (data, type, row, meta) {
                        return row.id;
                    }
                },
                {
                    data: 'proTitle', render: function (data, type, row) {
                        return '<span id="proTitle'+row.id+'">'+row.proTitle+'</span>';
                    }
                },
                {
                    data: 'proUnit', render: function (data, type, row) {
                        return '<span id="proUnit'+row.id+'">'+row.proUnit+'</span>';
                    }
                },
                {
                    data: 'supName', render: function (data, type, row) {
                        return '<span id="supName'+row.id+'">'+row.supName+'</span>';
                    }
                },


                {
                    data: 'proPrice', render: function (data, type, row, meta) {
                        // return ' <input type="text" class="form-control" id="inputPrice' + row.id + '" value="'+row.proPrice+'" placeholder="请输入进价">';
                        return '<span id="proPrice'+row.id+'">'+row.proPrice+'</span>';
                    }
                },
                {
                    data: 'proNum', render: function (data, type, row) {
                        return ' <input type="text" class="form-control" id="inputNumber' + row.id + '" value="'+row.proNum+'" placeholder="请输入退货数量">';
                    }
                },
            ],
        })
        //如果请求成功，弹起模态框
        $('#myModal').modal('show')
        console.log(resp.data.products);
    })
}
let selects=[]
/**
 * 将选中的商品添加到退货单种进行显示
 */
function save2RebackOrderList(){
    $("input[name='inp-product-box']:checked").each(function () {
        const product = {};
        if ($(this).prop('checked')) {
            //如果当前属性为checked
            product.id = $(this).val()
            product.proTitle=$('#proTitle'+product.id).text()
            product.proUnit=$('#proUnit'+product.id).text()
            product.supName=$('#supName'+product.id).text()
            product.proPrice=$('#proPrice' + product.id).text()
            product.proNum = $('#inputNumber' + product.id).val()
            product.eachSum = parseFloat(product.proPrice)*parseFloat(product.proNum)
            selects.push(product)
        }
    });
    console.log(selects)
    $('#myModal').modal('hide')
    //填充到外面表格中
    let rebackTable=$("#rebackOrderTable").DataTable({
        destroy: true,
        //数据源
        data: selects,
        //取消搜索栏
        bFilter: false,
        bLengthChange: false,
        paging: true,//表格分页
        //给每列赋值
        columns: [
            {
                data: 'id', render: function (data, type, row, meta) {
                    return '<input name="inp-product-box" class="inp-product-box" type="checkbox" value="' + row.id + '">'
                }
            },
            {
                data: 'id', render: function (data, type, row, meta) {
                    return row.id;
                }
            },
            {
                data: 'proTitle', render: function (data, type, row) {
                    return '<span id="proTitle'+row.id+'">'+row.proTitle+'</span>';
                }
            },
            {
                data: 'proUnit', render: function (data, type, row) {
                    return '<span id="proUnit'+row.id+'">'+row.proUnit+'</span>';
                }
            },
            {
                data: 'supName', render: function (data, type, row) {
                    return '<span id="supName'+row.id+'">'+row.supName+'</span>';
                }
            },


            {
                data: 'proPrice', render: function (data, type, row, meta) {
                    // return ' <input type="text" class="form-control" id="inputPrice' + row.id + '" value="'+row.proPrice+'" placeholder="请输入进价">';
                    return '<span id="proPrice'+row.id+'">'+row.proPrice+'</span>';
                }
            },
            {
                data: 'proNum', render: function (data, type, row) {
                    return '<span id="inputNumber'+row.id+'">'+row.proNum+'</span>';
                }
            },
            {
                data: 'eachSum', render: function (data, type, row) {
                    return '<span id="eachSum'+row.id+'">'+row.eachSum+'</span>';
                }
            },
        ],
    })
    //获取总价格
    let rows = $("#rebackOrderTable").dataTable().fnGetNodes()
    let sum=0;
    for(let i=0;i<rows.length;i++){
        // let data = $(rows[i].firstElementChild.firstElementChild)[5]
        let id = rows[i].children[1].firstChild.data
        let sumId='#eachSum'+id;
        sum+=parseFloat($(sumId).text())
    }
    $("#payMoney").val(sum)
}

/**
 * 保存进货退货单
 */
function showRebackOrderInfo(){
    let rebackOrder={}
    rebackOrder.orderId=$("#inputOrderNumber").val()
    rebackOrder.employeeId=$("#employeeSelect").val()
    rebackOrder.accountMoeny=$("#accountMoneySelect").val()
    rebackOrder.price=$("#payMoney").val()
    rebackOrder.back=$("#backup").val()
    rebackOrder.storeId=$("#storeSelect").val()
    rebackOrder.inputDate=$("#inpDate").val();
    rebackOrder.products=selects
    console.log(rebackOrder)

    $.ajax({
        type: 'post',
        url: "/admin/business/inputReback/unConnectSave",
        dataType: 'json',
        contentType: 'application/json;charset=utf-8',
        data: JSON.stringify(rebackOrder),
        success: function (resp) {
            console.log(resp)
            if (resp.data){
                toastr.success(resp.message,'提示')
                setTimeout(function () {
                    window.location.reload()
                },2000)
            }else{
                toastr.error(resp.message,'提示')
            }
        }
    });

}



function listSupplier(obj){
    $.ajax({
        type: 'get',
        url: "/admin/info/supplier/list",
        dataType: 'json',
        success: function (data) {
            let select = obj;
            for (var i = 0; i < data.length; i++) {
                select.append('<option value="' + data[i].id + '" >' + data[i].supName + '</option>');
            }
            select.selectpicker('refresh');
            select.selectpicker('render');
        }
    });
}



/**
 * 保存进货单据
 */
function saveInputOrder(){
    let inputOrder={}
    inputOrder.orderId = $('#checkInputOrderNumber').text()
    inputOrder.supplier= $('#supplierSelect').val()
    inputOrder.employeeId = $('#employeeSelect').val()
    inputOrder.accountMoeny = $('#accountMoneySelect').val()
    inputOrder.storeId = $('#storeSelect').val()
    inputOrder.inputDate = $("#inpDate").val()
    inputOrder.price = $('#sumMoney').text()
    inputOrder.back = $('#backup').val()
    inputOrder.products = localStorage.getItem("products");
    //商品信息
    console.log(inputOrder.products)
    console.log(inputOrder)
    localStorage.removeItem('productIds')
    $.ajax({
        type: 'post',
        url: "/admin/business/inputOrder/save",
        dataType: 'json',
        contentType: 'application/json;charset=utf-8',
        data: JSON.stringify(inputOrder),
        success: function (resp) {
            console.log(resp)
            if (resp.data){
                toastr.success(resp.message,'提示')
                setTimeout(function () {
                    window.location.reload()
                },2000)
            }else{
                toastr.error(resp.message,'提示')
            }
        }
    });
}



/**
 * 列出所有的支付账户信息
 */
function listMoneyAccount(obj) {
    $.ajax({
        type: 'get',
        url: "/admin/info/moneyAccount/list",
        dataType: 'json',
        success: function (data) {
            let select = obj;
            for (var i = 0; i < data.length; i++) {
                select.append('<option value="' + data[i].accId + '" >' + data[i].accName + '</option>');
            }
            select.selectpicker('refresh');
            select.selectpicker('render');
        }
    });
}



/**
 * 列出所有的库存地址
 * @param obj
 */
function listStores(obj) {
    $.ajax({
        type: 'get',
        url: "/admin/info/store/list",
        dataType: 'json',
        success: function (data) {
            let select = obj;
            for (var i = 0; i < data.length; i++) {
                select.append('<option value="' + data[i].bstoId + '" >' + data[i].bstoTitle + '</option>');
            }
            select.selectpicker('refresh');
            select.selectpicker('render');
        }
    });
}

/**
 * 列出所有的职工
 * @param obj
 */
function listEmployees(obj) {
    $.ajax({
        type: 'get',
        url: "/admin/info/employee/list",
        dataType: 'json',
        success: function (data) {
            let select = obj;
            for (var i = 0; i < data.length; i++) {
                select.append('<option value="' + data[i].id + '" >' + data[i].name + '</option>');
            }
            select.selectpicker('refresh');
            select.selectpicker('render');
        }
    });
}

/**
 * 默认进货日期
 * @param obj
 */
function setInputOrderDate(obj) {
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    obj.val(year + '-' + month + '-' + day)
}

/**
 * 设置单据编号
 */
function setInputOrderNumber(obj) {
    //日期格式化为指定格式
    Date.prototype.format = function (fmt) {
        var o = {
            "M+": this.getMonth() + 1,                 //月份
            "d+": this.getDate(),                    //日
            "h+": this.getHours(),                   //小时
            "m+": this.getMinutes(),                 //分
            "s+": this.getSeconds(),                 //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds()             //毫秒
        };

        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }

        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(
                    RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }

        return fmt;
    }
    obj.val(new Date().format("yyyyMMddhhmmss"))
}



